import React, { PureComponent } from 'react'
// import { stringify } from 'qs'
import { Table, Divider, notification, Button, Popconfirm, Alert } from 'antd'
import Viewer from 'react-viewer'
import { connect } from 'dva'
import router from 'umi/router'
import styles from './Index.less'
import columns from './columns'
import { exportList } from '../../../services/property'

// import { getValue } from '@/utils/utils'
@connect(({ loading, property, settings }) => ({
  settings,
  property,
  loading: loading.models.property,
}))
export default class List extends PureComponent {
  componentWillUnmount() {
    this.props.dispatch({
      type: 'property/updateState',
      payload: {
        selectedRowKeys: [],
      },
    })
  }

  handleAdd = () => {
    this.props.dispatch({
      type: 'property/updateState',
      payload: {
        currentItem: {},
      },
    })
    router.push('/property/update')
  }

  // 清除选择
  cleanSelectedKeys = () => {
    this.handleSelectRows([])
  }

  // 行选事件
  handleSelectRows = rows => {
    const { dispatch } = this.props
    dispatch({
      type: 'property/updateState',
      payload: {
        selectedRowKeys: rows,
      },
    })
  }

  // 查看图片
  handleShowImgClick = record => {
    const { dispatch } = this.props
    dispatch({
      type: 'property/images',
      payload: {
        id: record.id,
      },
    })
  }

  // 导出
  handleExportList = async () => {
    const { formValues } = this.props.property
    try {
      const res = await exportList({ current: 1, ...formValues })
      if (res && res.success) {
        window.open(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 编辑
  handleEditClick = record => {
    if (record.id) {
      this.props.dispatch({
        type: 'property/edit',
        payload: {
          id: record.id,
        },
      })
    } else {
      notification.error('没有选择记录')
    }
  }

  // 添加子资产
  handleAddChildClick = record => {
    //
    if (record.id) {
      //
      this.props.dispatch({
        type: 'property/updateState',
        payload: {
          currentItem: {},
        },
      })

      router.push({
        pathname: '/property/update',
        state: { pid: record.id, p_zcCode: record.zcCode },
      })
    } else {
      notification.error('没有选择记录')
    }
  }

  handleDelete = e => {
    e.preventDefault()
    const { selectedRowKeys } = this.props.property
    const { dispatch } = this.props
    dispatch({
      type: 'property/remove',
      payload: {
        ids: selectedRowKeys,
      },
    })
  }

  // 表格动作触发事件
  handleListChange = (pg, filtersArg, sorter) => {
    const { dispatch } = this.props
    const { formValues, pagination } = this.props.property
    if (sorter.field && pagination.currentPage === pg.current) {
      return
    }

    const params = {
      // size: pg.pageSize,
      ...formValues,
      current: pg.current,
      // ...filters,
    }

    dispatch({
      type: 'property/fetchList',
      payload: {
        ...params,
        type: 1,
      },
    })
  }

  handleViewClose = () => {
    this.props.dispatch({
      type: 'property/updateState',
      payload: {
        showView: false,
      },
    })
  }

  render() {
    const { loading } = this.props
    const { list, pagination, selectedRowKeys, showView, propImages } = this.props.property

    const rowSelectionProps = {
      selectedRowKeys,
      getCheckboxProps: record => ({
        //  报废不可删除
        disabled: record.status === '0004',
      }),
      onChange: selectedKeys => {
        this.handleSelectRows(selectedKeys)
      },
    }

    const propColumns = [
      ...columns,
      {
        title: '操作',
        align: 'center',
        width: 120,
        // fixed: 'right',
        render: (text, record) => (
          <div>
            <a onClick={e => this.handleShowImgClick(record, e)}>查看图片</a>

            {/* 非报废 */}
            {record.status !== '0004' ? (
              <React.Fragment>
                <Divider type="vertical" />
                <a onClick={e => this.handleEditClick(record, e)}>修改</a>
              </React.Fragment>
            ) : null}

            {/* 主资产 非报废 */}
            {record.zcType !== '0002' && record.status !== '0004' ? (
              <React.Fragment>
                <Divider type="vertical" />
                <a onClick={e => this.handleAddChildClick(record, e)}>添加子资产</a>
              </React.Fragment>
            ) : null}
          </div>
        ),
      },
    ]

    return (
      <div className={styles.standardTable}>
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            paddingTop: 15,
            paddingBottom: 15,
            backgroundColor: '#fff',
          }}
        >
          <div className={styles.tableTopbtns}>
            <Button icon="plus" type="primary" loading={loading} onClick={this.handleAdd}>
              新增资产
            </Button>
            <Popconfirm
              title={
                <span>
                  确定要删除所选中的资产信息吗？<br></br> 提示：删除主资产将同步删除子资产信息
                </span>
              }
              okText="确定"
              cancelText="取消"
              onConfirm={e => this.handleDelete(e)}
            >
              <Button type="danger" loading={loading}>
                删除
              </Button>
            </Popconfirm>
            <Button type="default" loading={loading} onClick={this.handleExportList}>
              导出Excel
            </Button>
          </div>
          <div className={styles.tableTopbtns}>
            {/* // TODO: 关联选项? */}
            <Button
              icon="printer"
              type="default"
              onClick={() => {
                router.push('/property/label')
              }}
            >
              打印标签
            </Button>
          </div>
        </div>
        <Alert
          style={{ marginBottom: 8 }}
          message={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              <a style={{ marginLeft: 24 }} onClick={() => this.handleSelectRows([])}>
                清空选择
              </a>
            </div>
          }
          type="info"
          showIcon
        />
        <Table
          loading={loading}
          size="small"
          bordered
          dataSource={list}
          rowKey={record => record.id}
          pagination={pagination}
          columns={propColumns}
          onChange={this.handleListChange}
          rowSelection={rowSelectionProps}
          // scroll={{ x: 800 }}
        />
        <Viewer visible={showView} onClose={this.handleViewClose} images={propImages} />
      </div>
    )
  }
}
